package com.eoner.managerlibrary.servertimer;

import android.util.Log;

import com.eoner.baselibrary.base.BasePresenter;
import com.eoner.managerlibrary.BuildConfig;
import com.eoner.managerlibrary.servertimer.api.ServerTimerRetrofit;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class ServerTimerManager extends BasePresenter {


    private static final long TIMER_DELAY = 60*1000;
    private static ServerTimerManager instance;
    //时间差
    private long timeDifferent = 0;

    //TODO:全局计时器
    private Timer mTimer;
    private MyTimerTask mTimerTask;
    private long mLotteryTime = 0;

    public static ServerTimerManager getInstance() {
        synchronized (ServerTimerManager.class) {
            if (instance == null) {
                instance = new ServerTimerManager();
            }
        }
        return instance;
    }

    private ServerTimerManager() {
        startTimerTask();
    }

    private synchronized long getTimeDifferent() {
        return timeDifferent;
    }

    private void setTimeDifferent(long timeDifferent) {
        this.timeDifferent = timeDifferent;
    }

    /**
    * 获取当前校准时间
    * */
    public long getCurrentTimeMillis() {
        long timeMillis = System.currentTimeMillis();
        //计算毫秒级
        long threeEnd = timeMillis - timeMillis/1000L * 1000;
        long currentTime = timeMillis/1000 + getTimeDifferent();
        return currentTime * 1000+threeEnd;
    }

    /**
     * 获取服务端时间
     * */
    public void requestServerTime() {
        ServerTimerRetrofit.getInstance().getServerTime().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<ServerTimeBean>() {
            @Override
            public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {

            }
            @Override
            public void onNext(@io.reactivex.annotations.NonNull ServerTimeBean bean) {
                if (bean!=null && bean.getCode().equals("0")){
                    long timeMillis = System.currentTimeMillis();
                    long threeEnd = timeMillis - timeMillis/1000L * 1000;
                    //判断毫秒级
                    if (threeEnd >= 500) {
                        setTimeDifferent(Long.parseLong(bean.getData().getTs()) - (timeMillis/1000)-1);
                        if (BuildConfig.DEBUG) {
                            Log.e("LiveLog LiveKit => E","服务时间1:"+bean.getData().getTs()+"  本地时间:"+(timeMillis/1000+1) + "  时间差:"+getTimeDifferent());
                        }
                    } else {
                        setTimeDifferent(Long.parseLong(bean.getData().getTs()) - (timeMillis/1000));

                        if (BuildConfig.DEBUG) {
                            Log.e("LiveLog LiveKit => E","服务时间2:"+bean.getData().getTs()+"  本地时间:"+timeMillis/1000 + "  时间差:"+getTimeDifferent());
                        }
                    }
                }
            }

            @Override
            public void onError(@io.reactivex.annotations.NonNull Throwable e) {
                e.printStackTrace();
            }

            @Override
            public void onComplete() {

            }
        });
    }

    /**
    * 开始任务
    * */
    private void startTimerTask() {
        if (mTimer == null) {
            mTimer = new Timer(true);
            mTimerTask = new MyTimerTask();
            //TODO:定时一分钟一校验
            mTimer.schedule(mTimerTask, TIMER_DELAY, TIMER_DELAY);
        }
    }

    /**
     * 定时开奖计时器
     */
    private class MyTimerTask extends TimerTask {
        public void run() {
            requestServerTime();
            if (BuildConfig.DEBUG) {
                Log.e("LiveLog LiveKit => E","校准时间:"+getCurrentTimeMillis() + "详细:"+ getDate2String(getCurrentTimeMillis(),"yyyy-MM-dd HH:mm:ss"));

            }
        }
    }

    /**
    * 停止任务
    * */
    public void stopTimerTask() {
        if (null != mTimer) {
            mTimerTask.cancel();
            mTimer = null;
        }
    }

    @Override
    public void onStart() {

    }

    public String getDate2String(long time, String pattern) {
        Date date = new Date(time);
        SimpleDateFormat format = new SimpleDateFormat(pattern, Locale.getDefault());
        return format.format(date);
    }
}
